import json
from PyQt5.Qt import *
from PyQt5.Qt import QThread
from PyQt5 import QtCore ,QtWidgets
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal
import time
import sys
from PyQt5 import uic
from visual import Visual_Class
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

class Window(QWidget):
    gui_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.msg_history=list()
        self.init_Thread()
    
    ### UI界面初始化
    def setup_ui(self):
        P1 = []
        ### 加载界面
        self.ui = uic.loadUi("./mainwindow.ui")
        self.ui.setWindowIcon(QIcon("./ic.ico"))
        self.label_title = self.ui.label_title                      
        self.label_title.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./IOA8.png);")
        
        ### 设置界面，重命名需要操作的空间
        self.label_camera = self.ui.label_camera
        self.textBrowser_log = self.ui.textBrowser_log
        
        ##设置相机页面
        self.pushButton_haikangCamera = self.ui.pushButton_haikangCamera
        self.pushButton_haikangCamera.clicked.connect(self.haikang_camera)

        self.pushButton_driverlessCamera = self.ui.pushButton_driverlessCamera
        self.pushButton_driverlessCamera.clicked.connect(self.driverless_camera)

        self.pushButton_otherCamera = self.ui.pushButton_otherCamera
        self.pushButton_otherCamera.clicked.connect(self.other_camera)
        
        ### 图像预处理页面
        self.lineEdit_ThreshValue = self.ui.lineEdit_ThreshValue

        self.pushButton_ThreshValueCompare = self.ui.pushButton_ThreshValueCompare
        self.pushButton_ThreshValueCompare.clicked.connect(self.ThreshValueCompare)

        self.pushButton_cropShow = self.ui.pushButton_cropShow
        self.pushButton_cropShow.clicked.connect(self.cropShow)

        self.lineEdit_crop_leftup_x = self.ui.lineEdit_crop_leftup_x
        self.lineEdit_crop_leftup_y = self.ui.lineEdit_crop_leftup_y
        self.lineEdit_crop_rightdown_x = self.ui.lineEdit_crop_rightdown_x
        self.lineEdit_crop_rightdown_y = self.ui.lineEdit_crop_rightdown_y

        self.pushButton_Erosion = self.ui.pushButton_Erosion
        self.pushButton_Erosion.clicked.connect(self.Erosion)

        self.comboBox_erosion = self.ui.comboBox_erosion
        self.comboBox_dilation = self.ui.comboBox_dilation

        self.pushButton_Dilation = self.ui.pushButton_Dilation
        self.pushButton_Dilation.clicked.connect(self.Dilation)

        ### 视觉算法页面
        self.pushButton_colorAlg = self.ui.pushButton_colorAlg
        self.pushButton_colorAlg.clicked.connect(self.colorAlg)

        self.pushButton_shapeAlg = self.ui.pushButton_shapeAlg
        self.pushButton_shapeAlg.clicked.connect(self.shapeAlg)

        self.pushButton_QRAlg = self.ui.pushButton_QRAlg
        self.pushButton_QRAlg.clicked.connect(self.QRAlg)

        self.pushButton_OCRAlg = self.ui.pushButton_OCRAlg
        self.pushButton_OCRAlg.clicked.connect(self.OCRAlg)

        ### 九点标定页面
        self.label_P1 = self.ui.label_P1
        self.label_P2 = self.ui.label_P2
        self.label_P3 = self.ui.label_P3
        self.label_P4 = self.ui.label_P4
        self.label_P5 = self.ui.label_P5
        self.label_P6 = self.ui.label_P6
        self.label_P7 = self.ui.label_P7
        self.label_P8 = self.ui.label_P8
        self.label_P9 = self.ui.label_P9

        self.lineEdit_P1 = self.ui.lineEdit_P1
        self.lineEdit_P2 = self.ui.lineEdit_P2
        self.lineEdit_P3 = self.ui.lineEdit_P3
        self.lineEdit_P4 = self.ui.lineEdit_P4
        self.lineEdit_P5 = self.ui.lineEdit_P5
        self.lineEdit_P6 = self.ui.lineEdit_P6
        self.lineEdit_P7 = self.ui.lineEdit_P7
        self.lineEdit_P8 = self.ui.lineEdit_P8
        self.lineEdit_P9 = self.ui.lineEdit_P9

        self.pushButton_calibrate = self.ui.pushButton_calibrate
        self.pushButton_calibrate.clicked.connect(self.calibrate)

        self.pushButton_cameraCoordinate = self.ui.pushButton_cameraCoordinate
        self.pushButton_cameraCoordinate.clicked.connect(self.cameraCoordinate)

        self.label_calibrateResult = self.ui.label_calibrateResult
    
    ### 信号进程初始化
    def init_Thread(self):
        self.gui_signal.connect(self.gui_signal_dispatch)
        ### 建立摄像头线程
        self.camera = Visual_Class(self.label_camera, self.gui_signal)   
        self.camera.start()

    def haikang_camera(self):
        pass

    def driverless_camera(self):
        self.camera.stop = True
        time.sleep(1)
        self.camera.stop = False
        self.camera.run()

    def other_camera(self):
        pass
    
    ### 阈值对比显示
    def ThreshValueCompare(self):
        self.log("阈值对比程序运行中...")
        thresh_value = self.lineEdit_ThreshValue.text()
        self.camera.thresh_value = int(thresh_value)
        self.camera.stop = False
        self.camera.program_flag = 1

    def cropShow(self):
        self.log("裁剪显示程序运行中...")
        x1 = int(self.lineEdit_crop_leftup_x.text())
        y1 = int(self.lineEdit_crop_leftup_y.text())
        x2 = int(self.lineEdit_crop_rightdown_x.text())
        y2 = int(self.lineEdit_crop_rightdown_y.text())
        val = [x1, y1, x2, y2]
        self.camera.crop_value = val
        ### 信号与槽函数的方式裁剪图像
        # self.camera.cap_signal.emit(json.dumps({"id":1,"value":val}))

        self.camera.stop = False
        #### 程序变量--标志位的方式传参裁剪图像
        self.camera.program_flag = 8

    def Erosion(self):
        self.log("图像处理腐蚀程序运行中...")
        self.camera.stop = False
        self.camera.Erosion_value = self.comboBox_erosion.currentText()
        self.camera.program_flag = 9

    def Dilation(self):
        self.log("图像处理膨胀程序运行中...")
        self.camera.stop = False
        self.camera.Dilation_value = self.comboBox_dilation.currentText()
        self.camera.program_flag = 10


    def colorAlg(self):
        self.log("颜色识别程序运行中...")
        self.camera.stop = False
        self.camera.program_flag = 2

    def shapeAlg(self):
        self.log("形状识别程序运行中...")
        self.camera.stop = False
        self.camera.program_flag = 3

    def QRAlg(self):
        self.log("二维码识别程序运行中...")
        self.camera.stop = False
        self.camera.program_flag = 4

    def OCRAlg(self):
        self.log("文字识别程序运行中...")
        self.camera.stop = False
        self.camera.program_flag = 5
    
    ### 九点标定--
    def calibrate(self):
        self.log("九点标定程序运行中...")
        self.camera.stop = False
        self.camera.program_flag = 6

    ### 九点标定结果显示
    def show_calibration(self):
        self.log("九点标定结果显示程序运行中...")
        self.label_calibrateResult.clear()
        self.label_calibrateResult.setText(self.camera.calibration_result)
        self.camera.stop = False

    ### 九点标定--robot坐标传给camera类，进行标定所用
    def on_line_value_changed(self,):
        P1 = self.lineEdit_P1.text()
        P2 = self.lineEdit_P2.text()
        P3 = self.lineEdit_P3.text()
        P4 = self.lineEdit_P4.text()
        P5 = self.lineEdit_P5.text()
        P6 = self.lineEdit_P6.text()
        P7 = self.lineEdit_P7.text()
        P8 = self.lineEdit_P8.text()
        P9 = self.lineEdit_P9.text()
        value = [P1,P2,P3,P4,P5,P6,P7,P8,P9]
        print(value)
        self.camera.cap_signal.emit(json.dumps({"id":2,"value":value}))

    def closeEvent(self, event):
        self.camera.stop()
        self.camera.join()
        event.accept()
    
    ### 九点标定--robot坐标传给camera类，进行标定所用
    def cameraCoordinate(self):
        self.camera.program_flag = 7

    ### 九点标定--相机像素坐标获取，并赋值到UI界面对应位置
    def pixelCoordinate(self):
        text_value1 = ', '.join(str(x) for x in self.camera.P1)
        text_value2 = ', '.join(str(x) for x in self.camera.P2)
        text_value3 = ', '.join(str(x) for x in self.camera.P3)
        text_value4 = ', '.join(str(x) for x in self.camera.P4)
        text_value5 = ', '.join(str(x) for x in self.camera.P5)
        text_value6 = ', '.join(str(x) for x in self.camera.P6)
        text_value7 = ', '.join(str(x) for x in self.camera.P7)
        text_value8 = ', '.join(str(x) for x in self.camera.P8)
        text_value9 = ', '.join(str(x) for x in self.camera.P9)

        self.label_P1.setText(text_value1) 
        self.label_P2.setText(text_value2)
        self.label_P3.setText(text_value3)
        self.label_P4.setText(text_value4)
        self.label_P5.setText(text_value5)
        self.label_P6.setText(text_value6)
        self.label_P7.setText(text_value7)
        self.label_P8.setText(text_value8)
        self.label_P9.setText(text_value9)

    def gui_signal_dispatch(self, msg):
        msg = json.loads(msg)
        ### 判断来自哪里的信号
        source = int(msg.get("source"))   
        data = msg.get("data")
        match source:
            case 0 :
                self.log("未能检测到9点全部坐标,请重新标定")
            
            case 1 :
                self.pixelCoordinate()
            
            case 2 :
                self.on_line_value_changed()
            
            case 3 :
                self.log("显示九点标定结果：转换矩阵输出")
                self.show_calibration()             
     
    ### 打印日志
    def log(self,msg):
        msg =time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+":  "+msg
        self.msg_history.append(msg)
        self.textBrowser_log.setText("<br>".join(self.msg_history))
        self.textBrowser_log.moveCursor(self.textBrowser_log.textCursor().End)
        # 更新内容，如果不更新可能没有显示新内容
        self.textBrowser_log.repaint()  

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.ui.show()
    app.exec()
